package com.weshare.nd.util;

import org.apache.log4j.Logger;

import java.io.*;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * 公共工具类
 * 
 * @author ysq
 *
 */
public class CommonUtil {
	static Logger logger = getLogger(CommonUtil.class);
	
	static String timeStr;
	static int tsn = 0;

	/**
	 * 获得log4j logger 对象
	 * 
	 * @param clazz
	 * @return
	 */
	public static Logger getLogger(Class<?> clazz) {
		Logger logger = Logger.getLogger(clazz);
		return logger;
	}

	/**
	 * 
	 * @param max
	 * @param min
	 * @return
	 */
	public static int getRundomNumber(int max, int min) {
		Random random = new Random();
		int result = random.nextInt(max) % (max - min + 1) + min;

		return result;
	}

	/**
	 * 生成唯一 id
	 * @return
	 */
	public static String getUniqueKey() {

		String dayType = "yyyyMMddHHmmssSSSS";
		String timeStamp = DateUtil.getNowTime(dayType);

		if (!timeStamp.equals(timeStr)) {
			timeStr = timeStamp;
			tsn = 0;
		} else {
			tsn++;
		}

		int ran = getRundomNumber(1000, 9999);

		String reuslt = timeStamp + "_" + ran + "_" + tsn;

		return reuslt;
	}

	/**
	 * 获得 getter 方法名
	 * 
	 * @param field
	 * @return
	 */
	public static String getGetterName(Field field) {
		StringBuffer buf = null;

		String fieldType = field.getType().getName();

		if ("boolean".equalsIgnoreCase(fieldType)) {// boolean
			buf = new StringBuffer("is");
		} else {
			buf = new StringBuffer("get");
		}

		String fieldName = field.getName();

		buf.append(fieldName.substring(0, 1).toUpperCase());

		buf.append(fieldName.substring(1));

		return buf.toString();
	}

	/**
	 * 获得 setter 方法名
	 * 
	 * @param field
	 * @return
	 */
	public static String getSetterName(Field field) {
		StringBuffer buf = new StringBuffer("set");

		String fieldName = field.getName();

		buf.append(fieldName.substring(0, 1).toUpperCase());

		buf.append(fieldName.substring(1));

		return buf.toString();
	}

	/**
	 * 获得 文本文件内容
	 * 
	 * @param path
	 * @return
	 */
	public static String getFileContent(String path) {
		StringBuilder builder = new StringBuilder();

		try {
			FileReader fr = new FileReader(path);
			BufferedReader reader = new BufferedReader(fr);
			String line = null;
			while ((line = reader.readLine()) != null) {
				builder.append(line);
				builder.append("\r\n");
			}

			reader.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return builder.toString();
	}

	/**
	 * 将文本写入文件
	 * 
	 * @param path
	 * @param content
	 * @param append
	 */
	public static void writeFileContent(String path, String content, boolean append) {
		FileWriter fw = null;
		BufferedWriter writer = null;
		try {
			fw = new FileWriter(path, append);
			writer = new BufferedWriter(fw);

			writer.write(content);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				writer.close();
				fw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 将数据写入文件
	 * 
	 * @param path
	 * @param dataByte
	 * @param append
	 */
	public static void writeFile(String path, byte[] dataByte, boolean append) {
		OutputStream output = null;
		try {
			output = new FileOutputStream(path, append);

			output.write(dataByte);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * byte 数组拼接追加
	 * 
	 * @param byteArrayList
	 * @return
	 */
	public static byte[] joinAllBytes(byte[]... byteArrayList) {

		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();

		for (byte[] oneArray : byteArrayList) {
			try {
				byteOut.write(oneArray);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		byte[] resultBytes = byteOut.toByteArray();

		byteOut.reset();
		try {
			byteOut.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return resultBytes;
	}

	/**
	 * byte 数组拼接追加
	 * 
	 * @param byteArrayList
	 * @return
	 */
	public static byte[] joinAllBytes(List<byte[]> byteArrayList) {

		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();

		for (byte[] oneArray : byteArrayList) {
			try {
				byteOut.write(oneArray);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		byte[] resultBytes = byteOut.toByteArray();

		byteOut.reset();
		try {
			byteOut.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return resultBytes;
	}

	/**
	 * 读取文件
	 * 
	 * @param path
	 * @return
	 */
	public static byte[] getFileData(String path) {
		byte[] resultByte = null;

		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		InputStream input = null;
		try {
			input = new FileInputStream(path);

			int readLength = 0;

			byte[] tmpByte = new byte[4 * 1024];

			while ((readLength = input.read(tmpByte)) > 0) {

				byteOut.write(tmpByte, 0, readLength);

			}

			resultByte = byteOut.toByteArray();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				input.close();

				byteOut.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return resultByte;
	}

	/**
	 * 转义字符
	 * 
	 * @param text
	 * @param key
	 * @return
	 */
	public static String escapeChar(String text, char key) {
		char spChar = '\\';
		StringBuilder builder = new StringBuilder();

		char[] charArray = text.toCharArray();

		for (char oneChar : charArray) {
			if (oneChar == key || oneChar == spChar) {
				builder.append("\\");
			}
			builder.append(oneChar);
		}
		String result = builder.toString();

		return result;
	}
	
	/**
	 * 创建文件包括目录
	 * @param pathFile
	 * @return
	 * @throws IOException 
	 */
	public static void createFile(File pathFile) throws IOException{
		File parentFile = pathFile.getParentFile();
		
		if(!parentFile.exists()){
			parentFile.mkdirs();
		}
		if(!pathFile.exists()){
			pathFile.createNewFile();
		}
	}
	
	/**
	 * 创建文件包括目录
	 * @param path
	 * @return
	 * @throws IOException 
	 */
	public static File createFile(String path) throws IOException{
		File resultFile = new File(path);
		
		createFile(resultFile);
		
		return resultFile;
	}

	/**
	 * 追加数组
	 *
	 * @param target
	 * @param append
	 * @return
	 */
	public static byte[] appendByte(byte[] target, byte[] append) {
		int originalLength = target.length;
		int appendLength = append.length;
		// 先扩容长度
		int totalLength = originalLength + appendLength;

		target = Arrays.copyOf(target, totalLength);

		System.arraycopy(append, 0, target, originalLength, appendLength);

		return target;
	}

	public static void main(String[] args) {

		
		logger.debug("debug ... ");
		logger.info("info ... ");
		logger.warn("warn ... ");
		logger.error("error ... ");
		
		System.out.println("finished ... ");
	}

}
